<template>
  <!-- 作业人员管理 -->
  <div class="relatedpartystaff">
    <basic-container>
      <avue-crud
        :option="option"
        :table-loading="loading"
        :data="data"
        :page.sync="page"
        :permission="permissionList"
        :before-open="beforeOpen"
        v-model="form"
        ref="crud"
        @row-update="rowUpdate"
        @row-save="rowSave"
        @row-del="rowDel"
        @search-change="searchChange"
        @search-reset="searchReset"
        @selection-change="selectionChange"
        @current-change="currentChange"
        @size-change="sizeChange"
        @refresh-change="refreshChange"
      >

        <!-- 左上方菜单栏 -->
        <template slot="menuLeft">
          <el-button
            type="danger"
            size="small"
            icon="el-icon-delete"
            plain
            @click="handleDelete">
            删 除
          </el-button>

          <!-- 导入 -->
        </template>

        <!-- 人员资质表单自定义 -->
        <template slot="ryzzForm">
          <div>
            <el-upload
              v-if="dialogType !== 'view'"
              action="/api/fileManager/upload/file"
              :headers="SetHeaders"
              :file-list="ryzzFileList"
              :before-upload="beforeUploadRYZZ"
              :on-remove="handleRemoveRYZZ"
              :on-success="uploadRYZZSuccess"
            >
              <el-button size="small" type="primary" icon="el-icon-document">选择文件</el-button>
            </el-upload>

            <a
              v-else
              v-for="(item, index) in ryzzFileList"
              :key="index"
              :href="downloadHead + item.response.data.id"
              style="color:#409EFF"
            >
              <i class="el-icon-download" style="margin-right:5px;"></i>下载文件（{{ item.name }}）
            </a>
          </div>
        </template>

        <!-- 培训资料表单自定义 -->
        <template slot="xgpxzlForm">
          <div>
            <el-upload
              v-if="dialogType !== 'view'"
              action="/api/fileManager/upload/file"
              :headers="SetHeaders"
              :file-list="xgpxzlFileList"
              :before-upload="beforeUploadXGPXZL"
              :on-remove="handleRemoveXGPXZL"
              :on-success="uploadXGPXZLSuccess"
            >
              <el-button size="small" type="primary" icon="el-icon-document">选择文件</el-button>
            </el-upload>

            <a
              v-else
              v-for="(item, index) in xgpxzlFileList"
              :key="index"
              :href="downloadHead + item.response.data.id"
              style="color:#409EFF"
            >
              <i class="el-icon-download" style="margin-right:5px;"></i>下载文件（{{ item.name }}）
            </a>
          </div>
        </template>

        <!-- 责任书表单自定义 -->
        <template slot="zrsForm">
          <div>
            <el-upload
              v-if="dialogType !== 'view'"
              action="/api/fileManager/upload/file"
              :headers="SetHeaders"
              :file-list="zrsFileList"
              :before-upload="beforeUploadZRS"
              :on-remove="handleRemoveZRS"
              :on-success="uploadZRSSuccess"
            >
              <el-button size="small" type="primary" icon="el-icon-document">选择文件</el-button>
            </el-upload>

            <a
              v-else
              v-for="(item, index) in zrsFileList"
              :key="index"
              :href="downloadHead + item.response.data.id"
              style="color:#409EFF"
            >
              <i class="el-icon-download" style="margin-right:5px;"></i>下载文件（{{ item.name }}）
            </a>
          </div>
        </template>

        <!-- 证书表单自定义 -->
        <template slot="zsForm">
          <div>
            <el-upload
              v-if="dialogType !== 'view'"
              action="/api/fileManager/upload/file"
              :headers="SetHeaders"
              :file-list="zsFileList"
              :before-upload="beforeUploadZS"
              :on-remove="handleRemoveZS"
              :on-success="uploadZSSuccess"
            >
              <el-button size="small" type="primary" icon="el-icon-document">选择文件</el-button>
            </el-upload>

            <a
              v-else
              v-for="(item, index) in zsFileList"
              :key="index"
              :href="downloadHead + item.response.data.id"
              style="color:#409EFF"
            >
              <i class="el-icon-download" style="margin-right:5px;"></i>下载文件（{{ item.name }}）
            </a>
          </div>
        </template>

      </avue-crud>
    </basic-container>
  </div>
</template>

<script>
import {
  getList,
  getDetail,
  add,
  update,
  remove
} from "@/api/basedata/interestedpartymange/relatedpartystaff";
import { mapGetters } from "vuex";
import { getToken } from "@/util/auth";

export default {
  props: {
    xgfdwId: {default: ""},
    addRelationDialog: {default: false}
  },
  data() {
    return {
      form: {},
      query: {},
      data: [],
      loading: true,
      selectionList: [],
      page: {
        pageSize: this.$pageSize,
        currentPage: 1,
        total: 0
      },
      option: {
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchSpan: 6,
        searchMenuSpan: 6,
        border: true,
        index: false,
        selection: true,
        viewBtn: true,
        refreshBtn: true,
        columnBtn: false,
        dialogClickModal: false,
        menuWidth: 200,
        column: [
          {
            label: "人员姓名",
            prop: "xm",
            align: "center",
            search: true,
            rules: [{
              required: true,
              message: "请输入姓名",
              trigger: "blur"
            }]
          },
          {
            label: "性别",
            prop: "xb",
            align: "center",
            type: "select",
            dicData: [{
              label: "男",
              value: 1
            }, {
              label: "女",
              value: 2
            }]
          },
          {
            label: "类别",
            prop: "lb",
            align: "center",
            rules: [{
              required: true,
              message: "请选择类别",
              trigger: "blur"
            }]
          },
          {
            label: "操作证号",
            prop: "czzh",
            align: "center"
          },
          {
            label: "身份证号",
            prop: "sfzh",
            align: "center",
            rules: [{
              required: true,
              message: "请输入身份证号",
              trigger: "blur"
            }]
          },
          {
            label: "作业类型",
            prop: "zylx",
            align: "center"
          },
          {
            label: "到期日期",
            prop: "dqrq",
            align: "center",
            type: "date",
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd"
          },
          {
            label: "备注",
            prop: "bz",
            align: "center",
            type: "textarea",
            span: 24,
            maxlength: 150
          },
          {
            label: "人员资质",
            prop: "ryzz",
            hide: true,
            formslot: true
          },
          {
            label: "培训资料",
            prop: "xgpxzl",
            hide: true,
            formslot: true
          },
          {
            label: "责任书",
            prop: "zrs",
            hide: true,
            formslot: true
          },
          {
            label: "证书",
            prop: "zs",
            hide: true,
            formslot: true
          }
        ]
      },
      // 人员资质
      dialogType: "",
      downloadHead: "/api/fileManager/download/",
      ryzzFileList: [],
      SetHeaders: { "Blade-Auth": getToken() },
      // 培训资料
      xgpxzlFileList: [],
      // 责任书
      zrsFileList: [],
      // 证书
      zsFileList: []
    };
  },
  computed: {
    ...mapGetters(["permission"]),

    // 按钮权限
    permissionList() {
      return {
        addBtn: true,//this.vaildData(this.permission.relatedpartystaff_add, false),
        viewBtn: true,//this.vaildData(this.permission.relatedpartystaff_view, false),
        delBtn: true,//this.vaildData(this.permission.relatedpartystaff_delete, false),
        editBtn: true,//this.vaildData(this.permission.relatedpartystaff_edit, false)
      };
    },

    // 勾选项ID
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  watch: {
    addRelationDialog() {
      if(this.addRelationDialog === true) {
        this.initData();
      }
    },
  },
  mounted() {
    this.initData();
  },
  methods: {

    // 初始化数据
    initData() {
      this.page.currentPage = 1;
      this.onLoad(this.page);
    },

    // 新增
    rowSave(row, done, loading) {
      row.xgfdw = this.xgfdwId;
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        },
        error => {
          loading();
          window.console.log(error);
        }
      );
    },

    // 修改
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        },
        error => {
          loading();
          console.log(error);
        }
      );
    },

    // 删除一条
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },

    // 删除多条
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },

    // 打开新增、修改、查看弹窗前
    beforeOpen(done, type) {
      this.dialogType = type;
      this.ryzzFileList = [];
      this.xgpxzlFileList = [];
      this.zrsFileList = [];
      this.zsFileList = [];
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
          if (this.form.ryzz && this.form.ryzzFile && JSON.stringify(this.form.ryzzFile) !== "{}") {
            this.ryzzFileList.push({
              name: this.form.ryzzFile.fileName,
              response: {
                code: 200,
                msg: "操作成功",
                success: true,
                data: this.form.ryzzFile
              }
            });
          }
          if (this.form.xgpxzl && this.form.xgpxzlFile && JSON.stringify(this.form.xgpxzlFile) !== "{}") {
            this.xgpxzlFileList.push({
              name: this.form.xgpxzlFile.fileName,
              response: {
                code: 200,
                msg: "操作成功",
                success: true,
                data: this.form.xgpxzlFile
              }
            });
          }
          if (this.form.zrs && this.form.zrsFile && JSON.stringify(this.form.zrsFile) !== "{}") {
            this.zrsFileList.push({
              name: this.form.zrsFile.fileName,
              response: {
                code: 200,
                msg: "操作成功",
                success: true,
                data: this.form.zrsFile
              }
            });
          }
          if (this.form.zs && this.form.zsFile && JSON.stringify(this.form.zsFile) !== "{}") {
            this.zsFileList.push({
              name: this.form.zsFile.fileName,
              response: {
                code: 200,
                msg: "操作成功",
                success: true,
                data: this.form.zsFile
              }
            });
          }
        });
      }
      done();
    },

    // 清空搜索条件
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },

    // 搜索条件改变
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },

    // 勾选
    selectionChange(list) {
      this.selectionList = list;
    },

    // 清空勾选
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },

    // 更换页数
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.onLoad(this.page);
    },

    // 更换每页显示数量
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.onLoad(this.page);
    },

    // 刷新
    refreshChange() {
      this.onLoad(this.page, this.query);
    },

    // 加载数据
    onLoad(page, params = {}) {
      this.loading = true;
      this.query["xgfdw"] = this.xgfdwId;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query)
      ).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },

    /**
     * 上传人员资质
     */

    // 上传人员资质前
    beforeUploadRYZZ(file) {
      console.log(file);
      var isLimit = this.ryzzFileList.length + 1 <= 1;
      if (!isLimit) {
        this.$message.warning("只能选择一个人员资质文件!");
      }
      return isLimit;
    },

    // 上传人员资质成功
    uploadRYZZSuccess(response, file, fileList) {
      if (response.code !== 200 || response.success !== true) {
        return;
      }
      this.ryzzFileList = fileList;
      this.form.ryzz = response.data.id;
    },

    // 删除人员资质
    handleRemoveRYZZ(file, fileList) {
      this.ryzzFileList = fileList;
      this.form.ryzz = "";
    },

    /**
     * 上传培训资料
     */

    // 上传培训资料前
    beforeUploadXGPXZL(file) {
      console.log(file);
      var isLimit = this.xgpxzlFileList.length + 1 <= 1;
      if (!isLimit) {
        this.$message.warning("只能选择一个培训资料文件!");
      }
      return isLimit;
    },

    // 上传培训资料成功
    uploadXGPXZLSuccess(response, file, fileList) {
      if (response.code !== 200 || response.success !== true) {
        return;
      }
      this.xgpxzlFileList = fileList;
      this.form.xgpxzl = response.data.id;
    },

    // 删除培训资料
    handleRemoveXGPXZL(file, fileList) {
      this.xgpxzlFileList = fileList;
      this.form.xgpxzl = "";
    },

    /**
     * 上传责任书
     */

    // 上传责任书前
    beforeUploadZRS(file) {
      console.log(file);
      var isLimit = this.zrsFileList.length + 1 <= 1;
      if (!isLimit) {
        this.$message.warning("只能选择一个责任书!");
      }
      return isLimit;
    },

    // 上传责任书成功
    uploadZRSSuccess(response, file, fileList) {
      if (response.code !== 200 || response.success !== true) {
        return;
      }
      this.zrsFileList = fileList;
      this.form.zrs = response.data.id;
    },

    // 删除责任书
    handleRemoveZRS(file, fileList) {
      this.zrsFileList = fileList;
      this.form.zrs = "";
    },

    /**
     * 上传证书
     */

    // 上传证书前
    beforeUploadZS(file) {
      console.log(file);
      var isLimit = this.zsFileList.length + 1 <= 1;
      if (!isLimit) {
        this.$message.warning("只能选择一个证书!");
      }
      return isLimit;
    },

    // 上传证书成功
    uploadZSSuccess(response, file, fileList) {
      if (response.code !== 200 || response.success !== true) {
        return;
      }
      this.zsFileList = fileList;
      this.form.zs = response.data.id;
    },

    // 删除证书
    handleRemoveZS(file, fileList) {
      this.zsFileList = fileList;
      this.form.zs = "";
    }

  }
};
</script>

<style></style>